package cloud.smalla.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 功能描述
 * Jwt工具类
 *
 * @author 邱彦祥
 * 时间：2023-03-31 11:23
 */
@Component
public class JwtUtils {

    private static long expire;

    private static String secret;

    private static String header;

    @Value("${va.jwt.expire}")
    public void setExpire(long expire) {
        JwtUtils.expire = expire;
    }

    @Value("${va.jwt.secret}")
    public void setSecret(String secret) {
        JwtUtils.secret = secret;
    }

    @Value("${va.jwt.header}")
    public void setHeader(String header) {
        JwtUtils.header = header;
    }

    public static String getSecret() {
        return secret;
    }

    // 生成JWT
    public static String generateToken(String key) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(key)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)    // 30天过期
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    // 解析JWT
    public static Claims getClaimsByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    // 判断JWT是否过期
    public static boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }

    public static String getHeader() {
        return header;
    }
}
